package com.supinfo.food.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;

import com.supinfo.food.define.Define;
import com.supinfo.food.entities.Dish;
import com.supinfo.food.entities.Order;
import com.supinfo.food.services.UpdateStates;
import com.supinfo.food.session.Session;
import com.supinfo.food.states.States;
import com.supinfo.food.tools.SerialisationTools;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.AdapterView.OnItemClickListener;

/**
 * Main pages
 * @author Keitaro
 * 
 */
public class CuisineActivity extends Activity {
	
	private static final int TIMER_TASK = 5000;
	private Session SESSION = Session.getInstance();
	private ListView mList;
	private SimpleAdapter mAdapter;
	private List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
	private Handler handler = new Handler();
	private Runnable thread;
	private AlertDialog alert;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.cuisine);
		this.setTitle("Order list");
		
		// Set list
		mList = (ListView) findViewById(R.id.orders);
		mAdapter = new SimpleAdapter(this, list, R.layout.listorder, new String[]{"orderId", "dishId", "statObject", "room", "name", "stat"}, new int[]{R.id.listOrder_orderId, R.id.listOrder_dishId, R.id.listOrder_statObject, R.id.listOrder_room, R.id.listOrder_name, R.id.listOrder_stat});
		mList.setAdapter(mAdapter);
		mList.setOnItemClickListener(new OnClick());
		
		// Launch task
		thread = new Runnable() {
			@Override
			public void run() {
				OrderWSAndroid orderTask = new OrderWSAndroid();
				orderTask.execute((Long) SESSION.getVarList().get("restaurant"));
			}
		};
		startHandler();
	}
	
	public void stopHandler() {
		handler.removeCallbacks(thread);
	}
	
	public void startHandler() {
		handler.postDelayed(thread, 0);
	}
	public void stopAlert() {
		alert.cancel();
	}
	
	/**
	 * Call WS for order list
	 * @author Keitaro
	 *
	 */
	private class OrderWSAndroid extends AsyncTask<Long, Void, SoapObject> {

		private static final String NAMESPACE = "android.services.food.supinfo.com";
		private static final String URL = Define.IP + "/services/OrderWSAndroid?wsdl";
		private static final String SOAP_ACTION = "OrderWSAndroid";
		private static final String METHOD_ACTION = "getByRestaurantForCuisine";
		private ProgressDialog dialog;
		
		@Override
		protected void onPreExecute() {
			dialog = ProgressDialog.show(CuisineActivity.this, "Loading", "Please wait...", true);
		}
		
		@Override
		protected SoapObject doInBackground(Long... params) {
			SoapObject reponse = null;
			try
		    {
		    	SoapObject request = new SoapObject(NAMESPACE, METHOD_ACTION);
		    	SoapSerializationEnvelope envelop = new SoapSerializationEnvelope(SoapEnvelope.VER11);
		    	request.addProperty("id", params[0]);
		    	envelop.setOutputSoapObject(request);
		    	AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(URL);
		    	androidHttpTransport.call(SOAP_ACTION, envelop);
		    	reponse = (SoapObject) envelop.bodyIn;
		    } catch (Exception e)
		    {
		    	Log.e("getRestaurants", "", e);
		    }
			return reponse;
		}
		
		@Override
		protected void onPostExecute(SoapObject result) {
			if (result == null || result.getProperty(0) == null)
				return ;
			
			@SuppressWarnings("unchecked")
			List<Order> resultList = (List<Order>) SerialisationTools.deserialisation(result.getProperty(0).toString());
			if (resultList == null)
				return ;
			SESSION.getVarList().put("orderList", resultList);
			
			// Creater list
			list.clear();
			for (Order order : resultList) {
				int i = 0;
				for (Dish key : order.getDish().keySet()) {
					HashMap<String, String> map = new HashMap<String, String>();
					map.put("orderId", order.getId().toString());
					map.put("dishId", String.valueOf(i++));
					map.put("room", order.getCustomer().getTable().getNumero());
		            map.put("name", key.getName());
		            map.put("stat", States.getTraduction(order.getDish().get(key)));
		            map.put("statObject", order.getDish().get(key).name());
		            list.add(map);
				}
			}
			mAdapter.notifyDataSetChanged();
			
			// Dialog
			dialog.dismiss();
			
			// Handler manager
			handler.postDelayed(CuisineActivity.this.thread, TIMER_TASK);
		}
		
	}
	
	/**
	 * Action on item
	 * @author Keitaro
	 *
	 */
	private class OnClick implements OnItemClickListener {

		public void onItemClick(AdapterView<?> a, View v, int position, long id) {
			// Stop handler
			stopHandler();
			
			@SuppressWarnings("unchecked")
			// Get order data
			final HashMap<String, String> map = (HashMap<String, String>) mList.getItemAtPosition(position);
			final Integer dishId = Integer.valueOf(map.get("dishId"));
			final Long orderId = Long.valueOf(map.get("orderId"));

			// Create popup
			Builder builderPopup = new Builder(CuisineActivity.this);
			builderPopup.setTitle("Choose the new state");
			CharSequence[] choices = new CharSequence[] {States.getTraduction(States.WAITING), States.getTraduction(States.PROCESSING), States.getTraduction(States.FINISHED), States.getTraduction(States.GIVEN)};
			builderPopup.setSingleChoiceItems(choices, States.position(States.valueOf(map.get("statObject"))), new DialogInterface.OnClickListener() {
				@SuppressWarnings("unchecked")
				@Override
				public void onClick(DialogInterface dialog, int which) {
					Order orderChoice = null;
					for (Order order : (List<Order>) SESSION.getVarList().get("orderList"))
						if (order.getId().equals(orderId))
							orderChoice = order;
					if (orderChoice != null) {
						int i = 0;
						for (Dish key : orderChoice.getDish().keySet())
							if (i++ == dishId)
								orderChoice.getDish().put(key, States.position(which));
						UpdateStates updateTask = new UpdateStates(CuisineActivity.this);
						updateTask.execute(SerialisationTools.serialisation(orderChoice));
					}
				}
			});
			alert = builderPopup.create();
			alert.show();
		}
		
	}
}
